package online.foxnull2.foxmall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import online.foxnull2.common.utils.R;
import online.foxnull2.foxmall.ware.entity.WareInfoEntity;
import online.foxnull2.foxmall.ware.feign.MemberFeignService;
import online.foxnull2.foxmall.ware.mapper.WareInfoMapper;
import online.foxnull2.foxmall.ware.service.WareInfoService;
import online.foxnull2.foxmall.ware.utils.PageUtils;
import online.foxnull2.foxmall.ware.utils.Query;
import online.foxnull2.foxmall.ware.vo.freight.FreightVo;
import online.foxnull2.foxmall.ware.vo.freight.MemberReceiveAddress;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoMapper, WareInfoEntity> implements WareInfoService {

    private final MemberFeignService memberFeignService;

    @Autowired
    public WareInfoServiceImpl(MemberFeignService memberFeignService) {
        this.memberFeignService = memberFeignService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        Object key = params.get("key");
        if (ObjectUtils.isNotEmpty(key)) {
            queryWrapper.and(wrapper -> wrapper.eq("id", key)
                    .or().like("name", key)
                    .or().like("address", key)
                    .or().like("areacode", key));
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FreightVo getFreightByAddressId(Long addressId) {
        R res = memberFeignService.info(addressId);
        MemberReceiveAddress memberReceiveAddress = res.getObj(new TypeReference<>() {
        });
        if (!ObjectUtils.isEmpty(memberReceiveAddress)) {
            String phone = memberReceiveAddress.getPhone();
            log.debug("phone {}", phone);

            return new FreightVo().setMemberReceiveAddress(memberReceiveAddress).setFreight(new BigDecimal(phone.substring(9, 10)));
        }

        return new FreightVo().setMemberReceiveAddress(memberReceiveAddress).setFreight(new BigDecimal("0"));
    }

}